//
//  ViewController.m
//  画板实现
//
//  Created by hyl on 16/6/29.
//  Copyright © 2016年 hyl. All rights reserved.
//

#import "ViewController.h"
#import "HYLImageHandleView.h"
#import "HYLDrawView.h"

@interface ViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet HYLDrawView *drawView;

@end

@implementation ViewController
#pragma mark - clear
- (IBAction)clear:(UIBarButtonItem *)sender {
    [_drawView clear];
}
#pragma mark _ cancel
- (IBAction)cancel:(UIBarButtonItem *)sender {
    [_drawView cancel];
}
#pragma mark - eraser
- (IBAction)eraser:(UIBarButtonItem *)sender {
    _drawView.pathColor=[UIColor whiteColor];
}
#pragma mark -pickerPhoto
- (IBAction)pickerPhoto:(UIBarButtonItem *)sender {
    UIImagePickerController *pickerVC=[[UIImagePickerController alloc]init];
    
    pickerVC.delegate=self;
    
    [self presentViewController:pickerVC animated:YES completion:nil];
}
#pragma mark - save
- (IBAction)save:(UIBarButtonItem *)sender {
    UIGraphicsBeginImageContext(self.drawView.bounds.size);
    CGContextRef context=UIGraphicsGetCurrentContext();
    [self.drawView.layer renderInContext:context];
    UIImage *image=UIGraphicsGetImageFromCurrentImageContext();
    
//    NSData *data=UIImageJPEGRepresentation(image, 1);
//    data writeToFile:<#(nonnull NSString *)#> atomically:<#(BOOL)#>
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    NSLog(@"保存成功");
}
#pragma mark - sliderChange
- (IBAction)sliderChange:(UISlider *)sender {
    _drawView.lineWidth=sender.value*10;
}
#pragma mark - redColor
- (IBAction)redColor:(UIButton *)sender {
    _drawView.pathColor=[UIColor redColor];
}
#pragma mark - blackColor
- (IBAction)blackColor:(UIButton *)sender {
    _drawView.pathColor=[UIColor blackColor];
}
#pragma mark - greenColor
- (IBAction)greenColor:(UIButton *)sender {
    _drawView.pathColor=[UIColor greenColor];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSLog(@"%@",info);
    UIImage *image=info[UIImagePickerControllerOriginalImage];
    
    HYLImageHandleView *imageHandView=[[HYLImageHandleView alloc]initWithFrame:self.drawView.bounds];
    
    imageHandView.imageView.image=image;
    //保存一份代码，当图片处理完时调用；
    imageHandView.imageHandleCompletionBlock=^(UIImage *image){
        self.drawView.image=image;
    };
    [self.drawView addSubview:imageHandView];
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
